// 导入路由模块
import router from "./router";
// 导入进度条模块
import nprogress from "nprogress";
import 'nprogress/nprogress.css'
import { transListToTreeData } from "@/utils";
import Layout from "@/views/Layout/index.vue";
import { useRouterConfig } from "./testAddRoute";
// import { useUserStore } from "@/stores/userStore";

const useRoute = useRouterConfig()
// 白名单
const whiteList =['/login','/404']

router.beforeEach(async(to,from,next)=>{
  // const useStore = useUserStore()
  nprogress.start()
  const user = JSON.parse(localStorage.getItem('user'))
  const userInfo = user?.userInfo
  const token = user?.userTokenInfo?.token
  if(token){
    // 用户已经登录了
    if(to.path==='/login'){
      next('/') //中转到主页
      nprogress.done()
    }
    else{
      // 如果还没有用户资料信息就去获取
      if(userInfo.uId){
        const rrs =  router.getRoutes()
        let i = rrs.findIndex(i=>i.path==='/')
        if( i===-1){
          const filtered = user.userInfo.permissions.filter((i) => i.isButton == false);
          const makedMenus = useRoute.makeMenuRoute(filtered)
          const treeMenu = transListToTreeData(makedMenus, 0);
          const rr = {
            path:'/',
            component:Layout,
            redirect:'/home',
            children:treeMenu
          }
          router.addRoute(rr)
          next(to.path)
        }else{
          next()
        }
      }else{
        next()
      }
      nprogress.done()
    }
  }else{
    // 用户没有登录
    // useStore.clearUserInfo()
    localStorage.clear()
    console.log(to.fullPath)
    if(whiteList.includes(to.path)){
      console.log(to)
      next()
    }else{
      next('/login')
      nprogress.done()
    }
  }
})

router.afterEach(()=>{
  nprogress.done()
})